import { getQueries } from '../services';
import { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { IQueryData, IState, MODELS, SUBJECTS } from '../typings';
import * as types from '../store/actionTypes';
import { Dispatch } from 'redux';

/**
 *  做题答题数据过程：
 *  数据请求 -> queryList -> curIdx -> state -> curQuestion -> setCurQuestion
 *  定义一个函数实现以上过程(自定义Hooks实现)
 *  1. 页面加载完毕时请求1次数据
 *  2. 将第一条题目数据 保存至curQuestion数组(新定义的)里
 *  3. 返回一个数组[curQuestion, setCurQuestion] 点击下一题时能够设置
 */
function useCurQuestion(): [IQueryData | null, any] {
  const dispatch: Dispatch = useDispatch();
  const [curQuestion, setCurQuestion] = useState<IQueryData | null>(null);

  //从state中获取参数
  const subject: SUBJECTS = useSelector((state: IState) => state.curSubject);
  const model: MODELS = useSelector((state: IState) => state.curModel);

  //数据请求
  //某一项[依赖项]发生变更重新获取数据
  useEffect(() => {
    getQueries<IQueryData[]>({
      subject,
      model
    }).then((data) => {
      //将请求后的数据存入state.queryList
      dispatch({ type: types.SET_QUERY_LIST, payload: data });

      //传入数据第一项到 数组curQuestion里
      setCurQuestion(data[0]);
    });
  }, [subject, model, dispatch]);

  //将数组curQuestion返回出去 包括修改这个数组的方法
  return [curQuestion, setCurQuestion];
}

export { useCurQuestion };
